(function($) {
    'use strict';
    
    $(document).ready(function() {
        // 为每个BattleRoundInline添加"加载更多"功能
        $('.inline-group').each(function() {
            var $inlineGroup = $(this);
            var $tabular = $inlineGroup.find('.tabular');
            
            // 检查是否是BattleRound inline
            if ($inlineGroup.find('input[name*="battleround"]').length > 0) {
                initLoadMoreRounds($inlineGroup, $tabular);
            }
        });
    });
    
    function initLoadMoreRounds($inlineGroup, $tabular) {
        var battleId = getBattleId();
        var loadedRounds = $tabular.find('tr.form-row').length;
        var isLoading = false;
        
        // 添加"加载更多"按钮
        var $loadMoreContainer = $('<div class="load-more-rounds"></div>');
        var $loadMoreBtn = $('<button type="button" class="load-more-btn">加载更多回合数据</button>');
        var $loadingMsg = $('<div class="rounds-loading" style="display:none;">正在加载...</div>');
        var $errorMsg = $('<div class="rounds-error" style="display:none;"></div>');
        
        $loadMoreContainer.append($loadMoreBtn, $loadingMsg, $errorMsg);
        $tabular.after($loadMoreContainer);
        
        // 绑定点击事件
        $loadMoreBtn.on('click', function() {
            if (isLoading) return;
            
            isLoading = true;
            $loadMoreBtn.prop('disabled', true);
            $loadingMsg.show();
            $errorMsg.hide();
            
            // Ajax请求加载更多回合
            $.ajax({
                url: '/admin/battles/battle/load-more-rounds/',
                method: 'GET',
                data: {
                    'battle_id': battleId,
                    'offset': loadedRounds,
                    'limit': 10
                },
                success: function(response) {
                    if (response.success && response.rounds.length > 0) {
                        appendRounds($tabular, response.rounds);
                        loadedRounds += response.rounds.length;
                        
                        // 如果没有更多数据，隐藏按钮
                        if (response.rounds.length < 10 || response.has_more === false) {
                            $loadMoreBtn.hide();
                            $loadMoreContainer.append('<div style="text-align:center;color:#666;font-style:italic;">已加载全部回合数据</div>');
                        }
                    } else {
                        $loadMoreBtn.hide();
                        $loadMoreContainer.append('<div style="text-align:center;color:#666;font-style:italic;">没有更多回合数据</div>');
                    }
                },
                error: function(xhr, status, error) {
                    $errorMsg.text('加载失败: ' + error).show();
                },
                complete: function() {
                    isLoading = false;
                    $loadMoreBtn.prop('disabled', false);
                    $loadingMsg.hide();
                }
            });
        });
        
        // 检查是否需要显示"加载更多"按钮
        if (loadedRounds >= 10) {
            checkHasMoreRounds(battleId, loadedRounds, $loadMoreBtn, $loadMoreContainer);
        } else {
            $loadMoreBtn.hide();
        }
    }
    
    function getBattleId() {
        // 从URL中提取battle ID
        var match = window.location.pathname.match(/\/admin\/battles\/battle\/(\d+)\//); 
        return match ? match[1] : null;
    }
    
    function checkHasMoreRounds(battleId, currentCount, $loadMoreBtn, $container) {
        $.ajax({
            url: '/admin/battles/battle/check-more-rounds/',
            method: 'GET',
            data: {
                'battle_id': battleId,
                'current_count': currentCount
            },
            success: function(response) {
                if (response.has_more) {
                    $loadMoreBtn.show();
                } else {
                    $loadMoreBtn.hide();
                    if (currentCount > 10) {
                        $container.append('<div style="text-align:center;color:#666;font-style:italic;">已显示全部回合数据</div>');
                    }
                }
            },
            error: function() {
                $loadMoreBtn.hide();
            }
        });
    }
    
    function appendRounds($tabular, rounds) {
        var $tbody = $tabular.find('tbody');
        var formsetPrefix = getFormsetPrefix($tabular);
        var currentFormCount = $tabular.find('tr.form-row').length;
        
        rounds.forEach(function(round, index) {
            var formIndex = currentFormCount + index;
            var $row = createRoundRow(round, formsetPrefix, formIndex);
            $tbody.append($row);
        });
        
        // 更新formset的TOTAL_FORMS
        updateTotalForms(formsetPrefix, currentFormCount + rounds.length);
    }
    
    function getFormsetPrefix($tabular) {
        var $firstInput = $tabular.find('input[name*="-"]').first();
        if ($firstInput.length) {
            var name = $firstInput.attr('name');
            return name.split('-')[0];
        }
        return 'battleround_set';
    }
    
    function createRoundRow(round, prefix, index) {
        var $row = $('<tr class="form-row"></tr>');
        
        // Round number
        var $roundNumCell = $('<td class="field-round_number"></td>');
        $roundNumCell.append('<input type="hidden" name="' + prefix + '-' + index + '-round_number" value="' + round.round_number + '">'); 
        $roundNumCell.append('<span class="round-number">' + round.round_number + '</span>');
        
        // Player 1 actions
        var $p1ActionsCell = $('<td class="field-player1_actions"></td>');
        $p1ActionsCell.append('<input type="hidden" name="' + prefix + '-' + index + '-player1_actions" value="' + (round.player1_actions || '') + '">');
        $p1ActionsCell.append('<div class="round-actions" title="' + (round.player1_actions || '') + '">' + (round.player1_actions || '-') + '</div>');
        
        // Player 2 actions  
        var $p2ActionsCell = $('<td class="field-player2_actions"></td>');
        $p2ActionsCell.append('<input type="hidden" name="' + prefix + '-' + index + '-player2_actions" value="' + (round.player2_actions || '') + '">');
        $p2ActionsCell.append('<div class="round-actions" title="' + (round.player2_actions || '') + '">' + (round.player2_actions || '-') + '</div>');
        
        // Timestamp
        var $timestampCell = $('<td class="field-timestamp"></td>');
        $timestampCell.append('<input type="hidden" name="' + prefix + '-' + index + '-timestamp" value="' + round.timestamp + '">');
        $timestampCell.append('<div class="round-timestamp">' + formatTimestamp(round.timestamp) + '</div>');
        
        // Hidden ID field
        $row.append('<input type="hidden" name="' + prefix + '-' + index + '-id" value="' + round.id + '">');
        
        $row.append($roundNumCell, $p1ActionsCell, $p2ActionsCell, $timestampCell);
        return $row;
    }
    
    function updateTotalForms(prefix, newTotal) {
        var $totalFormsInput = $('input[name="' + prefix + '-TOTAL_FORMS"]');
        if ($totalFormsInput.length) {
            $totalFormsInput.val(newTotal);
        }
    }
    
    function formatTimestamp(timestamp) {
        var date = new Date(timestamp);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit', 
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    }
    
})(django.jQuery);